package ai.people.netmon.msgsearch.service;

import ai.people.core.common.properties.elastic.ElasticIndex;
import ai.people.netmon.framework.domain.searchmsg.bean.*;
import ai.people.netmon.framework.domain.searchmsg.request.DataQuery;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.framework.model.response.Result;
import ai.people.netmon.framework.utils.ResultUtil;
import ai.people.netmon.msgsearch.config.ESProperties;
import ai.people.netmon.msgsearch.contants.SysContants;
import ai.people.netmon.msgsearch.domain.response.InfoDataResult;
import ai.people.netmon.msgsearch.mapstruct.InfoDataConverter;
import ai.people.netmon.utils.StringUtils;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@RefreshScope
@Service
public class SearchAfterServiceImpl {


    @Autowired
    private ESProperties esProperties;

    @Autowired
    private InfoDataConverter infoDataConverter;
    private static final String scrollUrl = "/_search/scroll";

    private static Set<String> ES_FIELDS_INT = new HashSet<>();


    /**
     * 匹配汉字
     */
    private final Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");

    static {
        ES_FIELDS_INT.add("user_id");
        ES_FIELDS_INT.add("group_id");
    }

    public Result search(DataQuery infoDataQuery, boolean or) {
        // 同步检索 普通检索
        return syncSearch(infoDataQuery, or);
        // 异步检索 普通检索
//        return asyncSearch(infoDataQuery);
    }

    public Result searchByStream(HttpServletResponse response, DataQuery infoDataQuery) {
        // 同步滚动检索检索 普通检索
        return syncSearchByScroll(response, infoDataQuery);
        // 异步检索 普通检索
//        return asyncSearch(infoDataQuery);
    }

    // 异步检索 普通检索
    private Result asyncSearch(DataQuery infoDataQuery) {
        Integer limit = infoDataQuery.getLimit();
        String source = infoDataQuery.getSource();
        Integer offset = infoDataQuery.getOffset();
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        String baseUrl = SysContants.ES_SERVER_URL;
        // 拼装url的source
        //String appendSource = this.appendSource(source);
        String appendSource = ElasticIndex.getIndexName(source);
        if (StringUtils.isBlank(appendSource)){
            return ResultUtil.success(PageResponse.builderEmpty());
        }
        String json = buildEsRequestBody(infoDataQuery, jsonMapper, false);

        StringBuilder url = new StringBuilder();
        url.append(baseUrl).append(appendSource).append("/_async_search");

        boolean isFirstParameterFlag = true;
        if (limit != null && limit > -1) {
            if (isFirstParameterFlag) {
                url.append("?");
                isFirstParameterFlag = false;
            } else {
                url.append("&");
            }
            url.append("size=").append(limit);
        }

        if (offset != null && offset > -1) {
            if (isFirstParameterFlag) {
                url.append("?");
                isFirstParameterFlag = false;
            } else {
                url.append("&");
            }
            url.append("from=").append(offset);
        }
        log.info("查询条件：" + json);
        log.info("查询链接：" + url);

        String result2 = HttpRequest.post(url.toString())
                .body(json)
                .execute().body();

        List<InfoDataResult> sourceInfos = new ArrayList<>();
        try {
            EsDataStreamQueryResult esQueryResult = bulidEsDataStreamQueryResult(jsonMapper, result2);
            log.info("运行状态:" + esQueryResult.getIs_running());
            if (esQueryResult.getId() != null) {
                while (true) {
                    if (!esQueryResult.getIs_running() || esQueryResult.getId() == null) {
                        break;
                    }
                    url = new StringBuilder();
                    url.append(baseUrl).append(appendSource).append("/_async_search").append("/").append(esQueryResult.getId());
                    result2 = HttpRequest.post(url.toString())
                            .body(json)
                            .execute().body();

                    log.info("查询链接：" + url);

                    esQueryResult = bulidEsDataStreamQueryResult(jsonMapper, result2);
                    bulidEsDataStreamResponseResult(sourceInfos, esQueryResult);
                }

            } else {
                bulidEsDataStreamResponseResult(sourceInfos, esQueryResult);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultUtil.success(sourceInfos);
    }


    // 同步检索 普通检索
    private Result syncSearch(DataQuery infoDataQuery, boolean or) {
        Integer limit = infoDataQuery.getLimit(); // 限制返回多少
        String source = infoDataQuery.getSource(); // 数据源
        Integer offset = infoDataQuery.getOffset(); // 偏移量，分页
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 拼装url的source
        //String appendSource = appendSource(source);
        String appendSource = ElasticIndex.getIndexName(source);
        if (StringUtils.isBlank(appendSource)){
            return ResultUtil.success(PageResponse.builderEmpty());
        }
        // 拼接es检索条件
        String json = buildEsRequestBody(infoDataQuery, jsonMapper, or);

        StringBuilder url = new StringBuilder();
        url.append(esProperties.getEsServiceUrl()).append(appendSource).append("/_search");

        boolean isFirstParameterFlag = true;
        if (limit != null && limit > -1) {
            if (isFirstParameterFlag) {
                url.append("?");
                isFirstParameterFlag = false;
            } else {
                url.append("&");
            }
            url.append("size=").append(Math.min(limit, esProperties.getFormSizeMaxSize()));
        }
        if (offset != null && offset > -1) {
            if (isFirstParameterFlag) {
                url.append("?");
                isFirstParameterFlag = false;
            } else {
                url.append("&");
            }
            url.append("from=").append(offset);
        }

        log.info("查询条件：" + json);
        log.info("查询链接：" + url);

        String result2 = HttpRequest.post(url.toString()).body(json).execute().body();
        List<InfoDataResult> sourceInfos = new ArrayList<>();
        try {
            EsQueryResult esQueryResult = bulidEsQueryResult(jsonMapper, result2);
            List<EsHit> hits = Optional.of(esQueryResult).map(EsQueryResult::getHits).map(EsHits::getHits).orElse(Collections.emptyList());
            bulidEsDataResponseResult(sourceInfos, hits);
            Long total = Optional.of(esQueryResult).map(EsQueryResult::getHits).map(EsHits::getTotal).map(EsHitsTotal::getValue).orElse(0L);
            PageResponse pageDataResponse = new PageResponse(sourceInfos, total);
            return new Result(pageDataResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.success(new PageResponse(sourceInfos, 0));
    }



    // 同步滚动检索检索 普通检索
    private Result syncSearchByScroll(HttpServletResponse response, DataQuery infoDataQuery) {
        response.setCharacterEncoding("UTF-8");

        Integer limit = Optional.ofNullable(infoDataQuery.getLimit()).orElse(esProperties.getScrollSizeTotal());
        String source = infoDataQuery.getSource();
        //Integer offset = infoDataQuery.getOffset(); // 偏移量，分页
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 拼装url的source
        //String appendSource = appendSource(source);
        String appendSource = ElasticIndex.getIndexName(source);
        if (StringUtils.isBlank(appendSource)){
            return ResultUtil.success(PageResponse.builderEmpty());
        }

        String json = buildEsRequestBody(infoDataQuery, jsonMapper, false);

        JSONObject query = JSON.parseObject(json);

        Map<String, String> sortMap = new HashMap<>();
        sortMap.put("id", "asc");
        List<Map<String, String>> sortList = new ArrayList<>();
        String sort = infoDataQuery.getSort();
        // 排序
        if (StringUtils.isNotBlank(sort)) {
            Map<String, String> dateOrder = new HashMap<>();
            //Map<String, Map<String, String>> dateSort = new HashMap<>();
            if ("+ps".equals(sort)) {
                dateOrder.put("date", "asc");
            } else if ("-ps".equals(sort)) {
                dateOrder.put("date", "desc");
            }
            sortList.add(dateOrder);

        }
        sortList.add(sortMap);
        query.put("sort", sortList);

        json = query.toString();
        StringBuilder url = new StringBuilder();
        url.append(esProperties.getEsServiceUrl()).append(appendSource).append("/_search");
        if (limit != null && limit > -1) {
            //url.append("&size=").append(Math.min(limit, esProperties.getScrollMaxSize()));
            //url.append("&size=").append(limit);
        }

        log.info("查询条件：" + json);
        log.info("查询链接：" + url);

        PrintWriter writer = null;
        // 滚动返回的数据量、limit的含义是返回的总量不是每页返回的条数（恩好确认） 2022-03-09 13:18:00
        long resultCount = 0;
        try {
            writer = response.getWriter();
            //String result = HttpRequest.post(url.toString()).body(json).execute().body();

            String result = HttpRequest.post(url.toString()).body(json).execute().body();
            EsQueryResult esQueryResult = bulidEsQueryResult(jsonMapper, result);
            boolean breakWhile = Optional.of(esQueryResult).map(EsQueryResult::getHits).map(EsHits::getHits).map(CollectionUtils::isEmpty).orElse(true);
            if (breakWhile) {
                responseWrite(response, writer, jsonMapper, null);
                return null;
            }
            resultCount += esQueryResult.getHits().getHits().size();
            responseWrite(response, writer, jsonMapper, esQueryResult);
            while (true) {
                // 第一次查询
                {
                    List<EsHit> hits = esQueryResult.getHits().getHits();
                    EsHit esHit = hits.get(hits.size() - 1);
                    InfoData infoData = JSON.parseObject(JSON.toJSONString(esHit.get_source()), InfoData.class);
                    List<String> searchAfter = new ArrayList<>();
                    if (StringUtils.isNotBlank(infoDataQuery.getSort())) {
                        searchAfter.add(infoData.getDate());
                    }
                    searchAfter.add(infoData.getId());
                    query.put("search_after", searchAfter);
                    json = query.toJSONString();
                    log.info("url:{} search_after查询条件 {}：", url, json);
                    result = HttpRequest.post(url.toString()).body(json).execute().body();
                    esQueryResult = bulidEsQueryResult(jsonMapper, result);
                }
                List<EsHit> esHits = Optional.ofNullable(esQueryResult).map(EsQueryResult::getHits).map(EsHits::getHits).orElse(null);
                if (CollectionUtils.isEmpty(esHits)) {
                    responseWrite(response, writer, jsonMapper, esQueryResult);
                    break;
                }
                resultCount += esHits.size();
                //scrollId = esQueryResult.get_scroll_id();
                responseWrite(response, writer, jsonMapper, esQueryResult);

                if (resultCount >= limit) {
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error("syncSearchByScrollError", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        return null;
    }


    // 构建ES检索返回结果,转换为对象
    private EsDataStreamQueryResult bulidEsDataStreamQueryResult(ObjectMapper jsonMapper, String result) {
        EsDataStreamQueryResult esQueryResult = null;
        try {
            esQueryResult = jsonMapper.readValue(result, EsDataStreamQueryResult.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return esQueryResult;
    }

    // 转换es数据为统一格式
    private void bulidEsDataStreamResponseResult(List<InfoDataResult> sourceInfos, EsDataStreamQueryResult esQueryResult) {
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        EsQueryResult esQueryResponse = esQueryResult.getResponse();
        if (esQueryResponse != null) {
            List<EsHit> hits = esQueryResponse.getHits().getHits();
            for (EsHit hit : hits) {
                try {
                    String source = jsonMapper.writeValueAsString(hit.get_source());
                    InfoData infoData = jsonMapper.readValue(source, InfoData.class);
                    InfoDataResult infoDataResult = infoDataConverter.toInfoDataResult(infoData);
                    sourceInfos.add(infoDataResult);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    //Trying to create too many scroll contexts. Must be less than or equal to: [500].
    //This limit can be set by changing the [search.max_open_scroll_context] setting
    // 构建ES检索返回结果,转换为对象
    public static EsQueryResult bulidEsQueryResult(ObjectMapper jsonMapper, String result) {
        EsQueryResult esQueryResult = null;
        try {
            esQueryResult = jsonMapper.readValue(result, EsQueryResult.class);
        } catch (JsonProcessingException e) {
            log.error(" jsonMapper.readValue-error", e);
        }
        return esQueryResult;
    }

    // 转换es数据为统一格式
    private void bulidEsDataResponseResult(List<InfoDataResult> sourceInfos, List<EsHit> hits) {
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //List<EsHit> hits = Optional.of(esQueryResult).map(EsQueryResult::getHits).map(EsHits::getHits).orElse(Collections.emptyList());
        //List<EsHit> hits = esQueryResult.getHits().getHits();
        List<String> groupId = new ArrayList<>();
        for (EsHit hit : hits) {
//            Map<String, Object> sourceInfo = (HashMap) hit.get_source();
//            sourceInfos.add(sourceInfo);
            try {
                String source = jsonMapper.writeValueAsString(hit.get_source());
                InfoData infoData = jsonMapper.readValue(source, InfoData.class);
                groupId.add(infoData.getGroup_id());
                InfoDataResult infoDataResult = infoDataConverter.toInfoDataResult(infoData);
                infoDataResult.setSentiment(infoData.getSentiment());
                if (!CollectionUtils.isEmpty(infoData.getTag())){
                    String tags = infoData.getTag().getJSONArray("tag").stream().map(String::valueOf).collect(Collectors.joining(","));
                    infoDataResult.setTags(tags);
                }
                if (Objects.equals(infoDataResult.getSource(),"news") && StringUtils.isBlank(infoDataResult.getContent())){
                    infoDataResult.setContent(infoDataResult.getTitle());
                }
                sourceInfos.add(infoDataResult);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        //db(groupId);
    }

    // 拼接es检索条件
    @Nullable
    private String buildEsRequestBody(DataQuery infoDataQuery, ObjectMapper jsonMapper, boolean or) {
        String keyword = infoDataQuery.getQ();
        GroupInfo group = infoDataQuery.getGroup();
        AuthorInfo author = infoDataQuery.getAuthor();
        String startDate = infoDataQuery.getPs();
        String endDate = infoDataQuery.getPe();
        String fields = infoDataQuery.getFields();
        String tags = infoDataQuery.getTags();
        String sort = infoDataQuery.getSort();
        String stream = infoDataQuery.getStream();
        Integer isFormat = infoDataQuery.getP();
        String partnerIds = infoDataQuery.getPartner_ids();
        String domain = infoDataQuery.getDomain();


        boolean appendOperatorFlag = false;
        StringBuilder sb = new StringBuilder();

        // 关键词
        if (StringUtils.isNotBlank(keyword)) {
            if (StringUtils.isNotBlank(domain)){
                sb.append("(domain\\*:").append("\"").append(domain).append("\"").append(") ");
                appendOperatorFlag = true;
            }

            // 只有是汉字才将空格转换成&
            boolean chineseCharacter = pattern.matcher(keyword).find();

            // 多个关键字中间有空格按照&逻辑查询  例：（北京 上海） 替换为 -> 北京&上海
            keyword = chineseCharacter ? keyword.trim().replaceAll("\\s+", "&") : keyword;

            String keywordForTypeStr = keyword.replaceAll("\\|", "\" OR \"").replaceAll("&", "\" AND \"");
            String keywordForTypeInt = keyword.replaceAll("\\|", " OR ").replaceAll("&", " AND ");

            if (appendOperatorFlag) {
                sb.append(" AND ");
            }
            if (StringUtils.isNotBlank(fields)) {
                String[] fieldSplit = fields.split(",");
                sb.append("(");
                keywordForTypeStr = "\"" + keywordForTypeStr + "\"";
                for (int i = 0; i < fieldSplit.length; i++) {
                    String fieldName = fieldSplit[i];
                    if (i > 0) {
                        sb.append(" OR (").append(fieldName).append("\\*:(").append(ES_FIELDS_INT.contains(fieldName) ? keywordForTypeInt : keywordForTypeStr).append(")) ");
                    } else {
                        sb.append(" (").append(fieldName).append("\\*:(").append(ES_FIELDS_INT.contains(fieldName) ? keywordForTypeInt : keywordForTypeStr).append(")) ");
                    }
                }
                sb.append(")");
            } else {
                sb.append(" (content\\*:").append("\"").append(keywordForTypeStr).append("\"").append(") ");
            }
            appendOperatorFlag = true;
        }
        // 开始截至日期
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            String format = "yyyy-MM-dd'T'HH:mm:ss'+0800'";
            String startDateNew = getDate(format, startDate);
            String endDateNew = getDate(format, endDate);
            if (appendOperatorFlag) {
                sb.append(" AND ");
            }
            sb.append(" (date:[").append(startDateNew).append(" TO ").append(endDateNew).append("])");
            //sb.append(" (ts:[").append(startDateNew).append(" TO ").append(endDateNew).append("])");
            appendOperatorFlag = true;
        }

        String concat = " AND ";

        boolean gid = group != null && StringUtils.isNotBlank(group.getId());

        boolean gname = group != null && StringUtils.isNotBlank(group.getName());

        boolean aid = author != null && StringUtils.isNotBlank(author.getId());

        boolean aname = author != null && StringUtils.isNotBlank(author.getName());

        List<String> all = new ArrayList<>();

        // 群组ID
        if (gid) {
            extracted(group.getId(), "group_id:", all);
        }
        // 群组name
        if (gname) {
            extracted(group.getName(), "group_name:", all);
        }
        // 账号ID
        if (aid) {
            extracted(author.getId(), "user_id:", all);
        }
        // 账号name
        if (aname) {
            extracted(author.getName(), "user_name:", all);
        }

        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(all)) {
            if (or) {
                concat = " OR ";
            }
            if (appendOperatorFlag) {
                sb.append(" AND ");
            }
            sb.append(" (").append(StringUtils.join(all, concat)).append(")");
        }

        // 标签
        if (StringUtils.isNotBlank(tags)) {
            String[] tagSplit = tags.split(",");
            if (tagSplit.length > 0) {
                if (appendOperatorFlag) {
                    sb.append(" AND ");
                }
                StringBuilder tagBuilder = new StringBuilder();
                for (int i = 0; i < tagSplit.length; i++) {
                    if (i > 0) {
                        tagBuilder.append(" AND ").append(tagSplit[i]);
                    } else {
                        tagBuilder.append(tagSplit[i]);
                    }
                }
                sb.append(" (tag:").append(tagBuilder).append(") ");
                sb.append(" (tag.tag:").append(tagBuilder).append(") ");
                appendOperatorFlag = true;
            }
        }

        String sentiment = infoDataQuery.getSentiment();
        //
        if (StringUtils.isNotBlank(sentiment)) {
            String[] sentiments = sentiment.split(",");
            if (sentiments.length > 0) {
                if (appendOperatorFlag) {
                    sb.append(" AND ");
                }
                StringBuilder tagBuilder = new StringBuilder();
                for (int i = 0; i < sentiments.length; i++) {
                    if (i > 0) {
                        tagBuilder.append(" AND ").append(sentiments[i]);
                    } else {
                        tagBuilder.append(sentiments[i]);
                    }
                }
                sb.append(" (sentiment:").append(tagBuilder).append(") ");
                appendOperatorFlag = true;
            }
        }

        //
        //String partnerIds = infoDataQuery.getPartner_ids();
        if (StringUtils.isNotBlank(partnerIds)) {
            String[] partnerId = partnerIds.split(",");
            if (partnerId.length > 0) {
                if (appendOperatorFlag) {
                    sb.append(" AND ");
                }
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < partnerId.length; i++) {
                    if (i > 0) {
                        builder.append(" AND ").append(partnerId[i]);
                    } else {
                        builder.append(partnerId[i]);
                    }
                }
                sb.append(" (partner_ids:").append(builder).append(") ");
                appendOperatorFlag = true;
            }
        }

        Map<String, Object> query = new HashMap<>();
        //130700
        if (sb.length() > 0) {
            Map<String, String> filterMap = new HashMap<>();
            filterMap.put("query", sb.toString());
            Map<String, Object> queryStringMap = new HashMap<>();
            queryStringMap.put("query_string", filterMap);
            // 查询
            query.put("query", queryStringMap);
        }

        query.put("track_total_hits", true);
        if (StringUtils.isNotBlank(keyword)) {
            query.put("min_score", 1.01);
        }
        // 排序
        if (StringUtils.isNotBlank(sort)) {

            Map<String, String> descOrder = new HashMap<>();
            descOrder.put("order", "desc");
            Map<String, String> ascOrder = new HashMap<>();
            ascOrder.put("order", "asc");

            List<Map<String, Map<String, String>>> sortList = new ArrayList<>();
            Map<String, Map<String, String>> dateSort = new HashMap<>();

            if ("+ps".equals(sort)) {
                dateSort.put("date", ascOrder);
                query.put("sort", dateSort);
            } else if ("-ps".equals(sort)) {
                dateSort.put("date", descOrder);
                query.put("sort", dateSort);
            }
        }

        String json = null;
        try {
            json = jsonMapper.writeValueAsString(query);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    private void extracted(String str, String field, List<String> all) {
        StringBuilder sb1 = new StringBuilder();
        String[] groupIds = str.split(",");
        sb1.append("(");
        for (int i = 0; i < groupIds.length; i++) {
            sb1.append(field).append(groupIds[i]);
            if (i != groupIds.length - 1) {
                sb1.append(" OR ");
            }
        }
        sb1.append(")");
        all.add(sb1.toString());
    }


    public static String getDate(String formate, String datetime) {
        String newDate = "";
        SimpleDateFormat sdf = new SimpleDateFormat(formate); // new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'+0800'");
        if (StringUtils.isNumber(datetime)) {
            Long startTimeMillis = Long.parseLong(datetime);
            if (datetime.length() == 10) {
                startTimeMillis = startTimeMillis * 1000;
            }
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(startTimeMillis);
            newDate = sdf.format(cal.getTime());
        } else {
            String ymdReg = "^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$";
            String ymdHmsReg = "^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\s+(20|21|22|23|[0-1]\\d):[0-5]\\d:[0-5]\\d$";
            if (StringUtils.isDate(ymdReg, datetime)) {
                try {
                    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(datetime);
                    newDate = sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else if (StringUtils.isDate(ymdHmsReg, datetime)) {
                try {
                    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datetime);
                    newDate = sdf.format(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return newDate;
    }


    private void responseWrite(HttpServletResponse response, PrintWriter writer, ObjectMapper jsonMapper, EsQueryResult esQueryResult) throws IOException {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html; charset=utf-8");
            if (esQueryResult == null) {
                writer.write("null\r\n");
                writer.flush();
                response.flushBuffer();
                return;
            }
            List<EsHit> hits = esQueryResult.getHits().getHits();
            for (EsHit hit : hits) {
                //Map<String, Object> sourceInfo = (HashMap) hit.get_source();
                String source = jsonMapper.writeValueAsString(hit.get_source());
                InfoData infoData = jsonMapper.readValue(source, InfoData.class);
                InfoDataResult infoDataResult = infoDataConverter.toInfoDataResult(infoData);
                writer.write(jsonMapper.writeValueAsString(infoDataResult) + "\r\n");
                writer.flush();
                response.flushBuffer();
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


    }



}
